<?php 
// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) {
    include("siteTop.php"); 
?>

<!--    
    Created By : Julian Ponce
    B.S. Computer Science - De La Salle Canlubang
    September 15, 2011
    Description :
    
    This page allows the user to receive the documents (Either Main Document
    or Attachment). If the document type is a Main Document, the user must
    satisfy all attachments in order to receive the documents/ "bundle".
-->
    
<?php 
    
    
    //GET THIS INFORMATION FROM DASHBOARD.PHP VIA POST METHOD.
    //THIS INFORMATION IS FOR TESTING PURPOSES ONLY.
    if(isset($_POST['documentsToReceive']))
    {
        $documentId = $_POST['documentsToReceive'];
        
    }
    else if(isset($_POST['documentsOnHand']))
    {
        $documentId = $_POST['documentsOnHand'];
    }
    else if(isset($_POST['taggedDocuments']))
    {
         $documentId = $_POST['taggedDocuments'];
    }
    $loggedUserId = $_SESSION['loggedUserId'];
    
    //CONNECT TO DATABASE
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    
    //IDENTIFIES THE SENDER OF THE DOCUMENT.
    $query = 
    "
        SELECT *
        FROM Log,Account
        WHERE Log.documentId = '$documentId' AND Log.userId = Account.userId AND activity = 'Sent'
        ORDER BY Log.logDateTime DESC

    ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    $senderId = $row['userId'];
    $senderName = $row['firstName'] . " " . $row['middleName'] . " " . $row['lastName'];
    
    //GET DOCUMENT TYPE IF MAIN DOCUMENT OR ATTACHMENT.
    mysql_free_result($result);
    $query = 
        "
            SELECT DocumentSetup.documentName, DocumentRoute.routeName
            FROM MainDocument, DocumentSetup, RouteStep, DocumentRoute
            WHERE mainDocumentId = '$documentId' AND 
                  MainDocument.documentSetupId = DocumentSetup.documentSetupId AND
                  MainDocument.currentStepId = RouteStep.stepId AND RouteStep.routeId = DocumentRoute.routeId
                  
        ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    
    //IF DOCUMENT TYPE == MAIN DOCUMENT
     if (mysql_num_rows($result) > 0) {
         $documentType = "MainDocument";
         $row = mysql_fetch_array($result);
         $documentName = $row['documentName'];
         $routeName = $row['routeName'];
         
         // GET PREVIOUS STEP ID BY CHECKING LOGS
        $query = 
            "
                SELECT stepId, logDateTime
                FROM Log
                WHERE documentId = '$documentId' AND activity = 'Sent'
                ORDER BY logDateTime DESC
            ";
         $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         $row = mysql_fetch_array($result);
         $prevStepId = $row['stepId'];
         $prevLogDateTime = $row['logDateTime'];
         
         
         //GET ATTACHMENTS OF THE MAIN DOCUMENT        
         $query = 
            "         
                SELECT Attachment.attachmentId, DocumentSetup.documentName, Attachment.location, DocumentSetup.documentSetupId
                FROM Attachment, DocumentSetup, Log
                WHERE (location = '$senderId' OR location = '$loggedUserId')AND
                      mainDocumentId = '$documentId' AND
                      Attachment.documentSetupId = DocumentSetup.documentSetupId AND
                      Log.documentId = Attachment.attachmentId AND
                      Log.stepId = '$prevStepId' AND Log.activity = 'Sent' AND
                      Log.logDateTime = '$prevLogDateTime' AND
                      Attachment.attachmentId NOT IN 
                        ( 
                            SELECT documentId AS attachmentId
                            FROM Sent_Attachment
                            WHERE receiveFlag != 'Merged'
                        )
            ";
         $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         
         //IF THERE ARE ATTACHMENTS
         if (mysql_num_rows($result) > 0) {
             $attachmentCount = mysql_num_rows($result);
            
            
         }
         
         //IF THERE ARE NO ATTACHMENTS FOR THE SPECIFIC MAIN DOCUMENT
         else if (mysql_num_rows($result) == 0){
             $attachmentCount = "0";
         }
     }

    //ELSE (ATTACHMENT)
     else {
         mysql_free_result($result);
         $documentType = "Attachment";
          $query = 
            "
                SELECT DocumentSetup.documentName
                FROM Attachment, DocumentSetup
                WHERE Attachment.attachmentId = '$documentId' AND Attachment.documentSetupId = DocumentSetup.documentSetupId
            ";
         $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
         $row = mysql_fetch_array($result);
         $documentName = $row['documentName'];
         
     }

   
    mysql_free_result($result);
    
    
    //END OF INITIAL QUERY IN IDENTIFYING DOCUMENT TYPE.
    
    if ($documentType == "MainDocument") {
        $documentTypeFull = "Main Document";
    }
    
    else {
        if ($documentType == "Attachment") {
            $documentTypeFull = "Attachment";
        }
    }

//    place query to identify if the passed document ID is an attachment or a main document.
//    return the document details 
    
?>
<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>
    <script src="js/jquery.alert.js"></script>

    <!-- CSS SOURCES -->
    <link rel="stylesheet" href="css/jquery.alert.css" type="text/css" />
    
    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
        jQuery(document).ready(function(){
            docTypeJS = ("<?php echo $documentType; ?>");
            attachmentCountJS = ("<?php echo $attachmentCount; ?>");         
           
           //jQueries in Receiving Main Document
            if (docTypeJS == "MainDocument") {                   
                   
                    //CREATE TABLE FOR ATTACHMENT RESULTS
                    if (attachmentCountJS > 0) {
                        jQuery.ajax({
                            type : 'POST',
                            url : 'ajaxRequests/getExistingAttachments.php',
                            dataType : 'json',
                            data: {
                                documentId : "<?php echo $documentId; ?>",
                                userId : "<?php echo $senderId; ?>"
                            },
                            success : function(data){
                                if (data) {
                                    jQuery.each(data, function(index, data) {
                                        if (data.received == 0) {
                                            jQuery("#lastRowAttachment").before("<tr><td><input type='hidden' class='rcvAttachmentFlag' value='0' id='flagRcv_" + data.attachmentId + "'/><span class='attachmentListClass' id='" + data.attachmentId +"'>" + data.documentName + "</span></td><td align='center'><img id='flagImg_" + data.attachmentId + "' src='images/ximage.png' height='20px' width='20px'/></td></tr>");
                                        }
                                            

                                        else if (data.received == 1) {
                                            jQuery("#lastRowAttachment").before("<tr><td><input type='hidden' class='rcvAttachmentFlag' value='1' id='flagRcv_" + data.attachmentId + "'/><span class='attachmentListClass' id='" + data.attachmentId +"'>" + data.documentName + "</span></td><td align='center'><img id='flagImg_" + data.attachmentId + "' src='images/checkmark.png' height='20px' width='20px'/></td></tr>");
                                        }
                                    });
                                }
                                    
                            },
                            error : function() {
                                alert("fail");
                            }
                        });
                        jQuery("#inputScan").focus();
                    }
                    
                    else {
                        jQuery("#attachmentHeader").after("<tr><td colspan='2'><span>This main document has no existing attachments.</span></td></tr>");
                        jQuery("#lastRowAttachment").hide();
                        jQuery("#attachmentHeader").hide();
                    }

                    
                // Focus the cursor to attachment scanner (#inputScan)
                
            }
           
           
            // START - INPUT SCAN WHEN ENTER KEY WAS PRESSED
            jQuery("#inputScan").keypress(function(e){
               if(e.keyCode == 13) {
                    jQuery("#inputScan").blur();
                    return false;
               }

            });
            
                
            // INPUT SCAN BLUR, THIS IDENTIFIES IF SCANNED ATTACHMENT IS IN ATTACHMENT LIST    
            jQuery("#inputScan").blur(function(){
                 
                 //CHECK IF TEXT BOX HAS CONTENT
                if (this.value != "") {
                    jQuery(".scanOutputMsg").html("");
                    scanValue = this.value;
                    attachmentFound = 0;
                    
                    //JQUERY EACH ALL ATTACHMENT ID IN ATTACHMENT LIST
                    jQuery(".attachmentListClass").each(function(index) {
                        if( scanValue == jQuery(this).attr('id') ) {
                            jQuery("#flagRcv_" + scanValue).val("1");
                            jQuery("#flagImg_" + scanValue).attr("src",'images/checkmark.png');
                            attachmentFound = 1;
                        }
                    });
                    
                    if (!attachmentFound) {
                        jQuery("#scanErrorMsg").html("Attachment with id '"+scanValue+"' not found.");
                    }
                    
                    // IF ATTACHMENT FOUND
                    else if (attachmentFound) {
                        jQuery("#scanSuccessMsg").html("Attachment with id '"+scanValue+"' found.");
                        tempRcvdAttachments = jQuery("#receivedAttachments").val();
                        tempRcvdAttachmentsCount = jQuery("#receivedAttachmentsCount").val();
                        tempRcvdAttachmentsCount = parseInt(tempRcvdAttachmentsCount);
                        tempRcvdAttachmentsCount++;
                        jQuery("#receivedAttachmentsCount").val(tempRcvdAttachmentsCount);
                        
                        if (tempRcvdAttachments == "") {
                            jQuery("#receivedAttachments").val(scanValue);
                        }
                        
                        else {
                            tempRcvdAttachments = tempRcvdAttachments + "," + scanValue;
                            jQuery("#receivedAttachments").val(tempRcvdAttachments);
                        }
                        
                        // THIS VERIFIES IF ATTACHMENTS ARE ALREADY COMPLETE
                        attachmentsComplete = 1;
                        jQuery(".rcvAttachmentFlag").each(function(index) {
                            if (this.value == 0) {
                                attachmentsComplete = 0;
                            }
                        });
                        
                        // IF ATTACHMENTS ARE COMPLETE, AUTO SUBMIT OF DONE BUTTON.
                        if (attachmentsComplete) {
                            jQuery("#doneButton").click();
                        }
                    }
                      
                      
                    jQuery("#inputScan").val("");
                    jQuery("#inputScan").focus();
                }
                
            }); //END OF SCAN INPUT BLUR
            
            
            // RESET VALUE OF SCAN TEXT IF CLICKED.
            jQuery("#inputScan").click(function() {
                jQuery(this).val("");
                jQuery("#scanErrorMsg").html("");
            });
                

            // CANCEL BUTTON CLICKED > REDIRECT TO dashboard.php
            jQuery("#cancelButton").click(function() {
                var alertOption=window.confirm("Are you sure you want to cancel?")
                if (alertOption) {
                    window.location = 'dashboard.php';
                }
                
            });
            
            
            // DONE BUTTON CLICKED
            jQuery("#doneButton").click(function() {
                jQuery("#plsWaitDiv").show();
                jQuery(".rcvngBtns").hide();
                
                
                // IF THERE ARE NEWLY RECEIVED ATTACHMENTS.
                if (attachmentCountJS > 0) {
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/recordReceivedDocuments.php',
                        dataType : 'json',
                        data: {
                            documentId : "<?php echo $documentId; ?>",
                            senderId : "<?php echo $senderId; ?>",
                            rcvdAttachmentsArray : jQuery("#receivedAttachments").val(),
                            attachmentCount : parseInt(jQuery("#receivedAttachmentsCount").val())
                        },
                        success : function(data){
                            attachCount = jQuery("#receivedAttachmentsCount").val();
                            
                            if ( attachCount != "0") {
                                jQuery("#dashboardMessage").val(attachCount + " attachment/s of main document (<?php echo $documentId; ?>) successfully received.");
                                
                                // ALERT OPTION/CONFIRMATION FOR REDIRECTION
                                var alertOption=window.confirm("Do you want to view the document?")
                                
                                // VIEW PAGE SENDING REDIRECT
                                if (alertOption) {
                                    jQuery("#passedDocumentId").val("<?php echo $documentId; ?>");
                                    jQuery("#viewPageSendingForm").submit();
                                }
                                
                                // DASHBOARD REDIRECT
                                else {
                                    jQuery("#dashboardMessageForm").submit();
                                }
                            }
                            
                            else {
                               jQuery("#dashboardMessage").val("No received attachment for main document (<?php echo $documentId; ?>).");
                               jQuery("#dashboardMessageForm").submit();
                            }
                        },
                        error : function() {

                        }
                    });
                }
                
                // NO ATTACHMENTS > RECEIVE DOCUMENT.
                else {
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/makeMainDocumentReceived.php',
                        dataType : 'json',
                        data: {
                            documentId : "<?php echo $documentId; ?>"
                        },
                        success : function(data){
                            window.location = 'dashboard.php';
                        },
                        error : function() {
                            alert("fail in AJAX [makeMainDocumentReceived.php]");
                        }
                    });
                }
                
            });

        }); // END - (DOCUMENT READY FUNCTION)
    </script>
    <!-- HEAD END -->


<?php include("siteMiddle.php"); ?>
    
<!-- START OF BODY -->
<div id="content">
    <h1>Receiving ( <?php echo $documentTypeFull ?> )</h1>
    
    <?php
    // Check permission
    $thePermissions = array('VIEWMAIN');
    if ( checkPermission( $thePermissions, $userId ) == true ) {
    ?>
    
    <form>
        <span class="screenlet" >Document Information</span>
        <table>
            <tr></tr>
            <tr><td>Document Type : </td>
                <td>
                    <!--IDENTIFY IF DOC TYPE = MAIN DOCUMENT / ATTACHMENT-->
                    <?php
                    echo $documentTypeFull;
                    ?>
                </td>
            </tr>            
            <tr><td>Document Name : </td>
                <td>
                    <span><?php echo $documentName; ?></span>
                </td>
            </tr>

<!-- If Document type = Main Document, show Document Route-->
<?php if ($documentType == "MainDocument") { ?>
                <tr><td>Document Route : </td>
                    <td>
                        <span><?php echo $routeName; ?></span>
                    </td>
                </tr>
<?php } ?>
                
            <tr><td>Document ID : </td>
                <td>
                    <span><?php echo $documentId; ?></span>
                </td>
            </tr>
            
            <tr>
                <td>Document Labels : </td>
                <td>
                    <?php
                        // Add label of the document. 
                        // Include was done since it is both using by: viewPageSending and viewPageReceiving
                        $mainDocId = $documentId;
                        include('includes/functions/showLabels.php'); 
                    ?>
                </td>
            </tr>
            
            <tr>
                <td>Sender : </td>
                <td>
                    <span><?php echo $senderName; ?></span>
                </td>
            </tr>
        </table>

<?php if ($documentType == "MainDocument") { ?>
    <span class="screenlet" >Attachments</span>
    <table border="1">
        <tr id="attachmentHeader">
            <th>Name</th>
            <th>Received?</th>
        </tr>
        <tr id="lastRowAttachment">
            <td colspan="2" class="scanClassBig">
                <span>Attachment Id :</span>
                <br>
                <input type="text" id="inputScan" />
                <br>
                <span class="errorMessage scanOutputMsg" id="scanErrorMsg"></span>
                <span class="successMessage scanOutputMsg" id="scanSuccessMsg"></span>
            </td>
        </tr>
    </table>
    <input type="hidden" name="receivedAttachments" id="receivedAttachments"/>
    <input type="hidden" name="receivedAttachmentsCount" id="receivedAttachmentsCount" value="0"/>

<?php } ?>

    <!-- RECEIVE BUTTON -->
    <input type="Button" name="doneButton" id="doneButton" class="siteGreenButton rcvngBtns" value="Done" />
    
    <!-- CANCEL BUTTON -->
    <input type="Button" name="cancelButton" id="cancelButton" class="siteRedButton rcvngBtns" value="Cancel" />
    </form>
    
     <!-- PLEASE WAIT DIV -->
    <div id="plsWaitDiv" style="display: none;">
        <img src='images/others/loading_1.gif' height='15px' width='15px' /> Please wait
    </div>
    
    
    <!-- DASHBOARD FORM -->
    <form id="dashboardMessageForm" action="dashboard.php" method="POST" target="_self">
        <input type="hidden" name="successMessages" id="dashboardMessage"value=""/>
    </form>
    
    <!-- VIEW PAGE SENDING FORM -->
    <form id="viewPageSendingForm" action="viewPageSending.php" method="POST" target="_self">
        <input type="hidden" name="passedDocumentId" id="passedDocumentId"value=""/>
    </form>
    
    <?php
    }
    else {
        echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
    }
    // End checking permission
    ?>
</div> 

<!-- BODY END -->
<?php 
    include ("siteBottom.php"); 
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
 echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>